package com.cloudcross.ssp.web.advertiser.main.finance;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.cloudcross.ssp.base.utils.freemarker.FreemarkerTemplateProcessor;
import com.cloudcross.ssp.base.web.SimpleController;
import com.cloudcross.ssp.common.utils.Pager;
import com.cloudcross.ssp.model.Account;
import com.cloudcross.ssp.model.Finance;
import com.cloudcross.ssp.service.IAdvBalanceService;
import com.cloudcross.ssp.service.IAdvertiserService;
import com.cloudcross.ssp.service.IFinanceService;

@Controller
@RequestMapping("/advertiser/main/finance/finance-data")
public class FinanceDataController extends SimpleController {

    @Autowired
    protected IFinanceService financeService;

    @Autowired
    private IAdvBalanceService advBalanceService;

    @Autowired
    private FreemarkerTemplateProcessor templateProcessor;
    @Autowired
    private IAdvertiserService advertiserService;

    @RequestMapping
    public String index(Model model) {
        return redirect(page("list"));
    }

    /**
     * 资金管理列表页控制
     * 前端要传递一个广告主id变量名为selectedAdvertiserId，如果是空值或者是空字符串或者是-1表示的是全部广告主，没传默认也表示全部的广告主
     * 
     * @param model
     * @param paramMap
     * @param page
     * @return
     */
    @RequestMapping("/list")
    public String list(Model model, @RequestParam HashMap<String, Object> paramMap, @RequestParam(defaultValue = "1") int page) {

        // 获取当前登录的帐号
        Account account = getLoginUser();
        model.addAttribute("loginAccountName", account.getAccountName());
        model.addAttribute("advertiserIdFinance", account.getAdvertiserId());
        Long agentId = null;
        Long advertiserId = null;

        /**
         * 判断登录用户是广告主还是广告主代理商，广告主则advertiserId和agentId都不为0
         * 广告主代理商则是agentId不为0，advertiserId等于0
         */
        // 下面判断是广告主
        if (0 != account.getAdvertiserId() && 0 != account.getAgentId()) {
            advertiserId = account.getAdvertiserId();
        }

        // 下面判断是代理商，一般都是代理商登录的
        if (0 != account.getAgentId() && 0 == account.getAdvertiserId()) {
            agentId = account.getAgentId();

            // 如果是代理商账号的话，也要传递一个代理商账号的余额
            Double agentBalance = advBalanceService.findBalanceByAgentId(agentId);

            // 如果找到的余额为空则设为0
            if (null == agentBalance) {
                agentBalance = new Double(0);
            }
            model.addAttribute("agentBalance", agentBalance);
        }

        String advertiserName = "全部广告主";
        if (null == paramMap.get("selectedAdvertiserId") || "".equals(paramMap.get("selectedAdvertiserId"))) {
            advertiserName = "全部广告主";
        } else {
            if (-1 == Long.parseLong((String) paramMap.get("selectedAdvertiserId"))) {
                advertiserName = "全部广告主";
            } else {
                advertiserId = Long.parseLong((String) paramMap.get("selectedAdvertiserId"));
                advertiserName = (String) paramMap.get("selectedAdvertiserName");
            }
        }

        paramMap.put("agentId", agentId);
        paramMap.put("advertiserId", advertiserId);
        paramMap.put("selectedAdvertiserName", advertiserName);

        int totalRow = financeService.countByParams(paramMap);
        Pager pager = new Pager();
        pager.setPage(page);
        pager.setTotalRow(totalRow);

        List<Finance> financeList = financeService.findByParams(paramMap, pager);

        model.addAllAttributes(paramMap);
        model.addAttribute("pager", pager);
        model.addAttribute("financeList", financeList);

        return page("financelist");
    }

    /**
     * 资金分配跳转
     */
    @RequestMapping("/allocation")
    public String edit(Model model, @RequestParam Long advertiserId) {
        // 得到当前登录用户
        Account account = getLoginUser();
        // 得到该代理商的账户余额
        Double agentBalance = advBalanceService.findBalanceByAgentId(account.getAgentId());
        // 如果找到的余额为空则设为0
        if (null == agentBalance) {
            agentBalance = new Double(0);
        }
        model.addAttribute("agentBalance", agentBalance);
        model.addAttribute("advertiserId", advertiserId);
        return page("allocation");
    }

    /**
     * 资金分配保存 保存时存两条记录，一条是代理商的分配记录，一条是广告主分配的记录（就是广告主被分配到多少钱）
     * 要接收三个参数值，分别是要分配给那个广告主的id(变量名为advertiserId)，分配金额(变量名为allocate),备注(变量名为memo)
     * 
     * @param model
     * @return
     */
    @RequestMapping("/save")
    public String save(Model model, @RequestParam HashMap<String, Object> paramMap) {

        // 得到登录账号
        Account account = getLoginUser();
        paramMap.put("agentId", account.getAgentId());
        paramMap.put("accountId", account.getId());

        // 将代理商的余额减掉分配的钱，以得到代理商的余额
        Double agentBalance = advBalanceService.findBalanceByAgentId(account.getAgentId());
        // 如果找到的余额为空则设为0
        if (null == agentBalance) {
            agentBalance = new Double(0);
        }
        paramMap.put("agentBalance", (agentBalance - Double.parseDouble((String) paramMap.get("allocate"))));

        // 将广告主的余额加上所分配到的钱，得到广告主的余额
        Double advertiserBalance = advBalanceService.findBalanceByAdvertiserId(Long.parseLong(String.valueOf(paramMap.get("advertiserId"))));
        // 如果找到的余额为空则设为0
        if (null == advertiserBalance) {
            advertiserBalance = new Double(0);
        }
        paramMap.put("advertiserBalance", (advertiserBalance + Double.parseDouble((String) paramMap.get("allocate"))));

        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmSS");
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        paramMap.put("num", sdf.format(new Date()));
        paramMap.put("actTime", sdf1.format(new Date()));

        // 保存分配
        financeService.saveAllocation(paramMap);

        return redirect(page("list"));
    }

    /**
     * 资金管理导出excel
     * 前端要传递一个广告主id变量名为selectedAdvertiserId，如果是空值或者是空字符串或者是-1表示的是全部广告主，没传默认也表示全部的广告主
     * 
     * @param model
     * @param request
     * @param response
     * @param paramMap
     */
    @RequestMapping("/exportDataReportExcel")
    public void exportDataReportExcel(Model model, HttpServletRequest request, HttpServletResponse response,
            @RequestParam Map<String, Object> paramMap) {
        Long agentId = null;
        Long advertiserId = null;
        // 得到当前登录用户
        Account account = getLoginUser();

        /**
         * 判断登录用户是广告主还是广告主代理商，广告主则advertiserId和agentId都不为0
         * 广告主代理商则是agentId不为0，advertiserId等于0
         */
        // 下面判断是广告主
        if (0 != account.getAdvertiserId() && 0 != account.getAgentId()) {
            advertiserId = account.getAdvertiserId();
        }

        // 下面判断是代理商，一般都是代理商登录的
        if (0 != account.getAgentId() && 0 == account.getAdvertiserId()) {
            agentId = account.getAgentId();
        }

        String advertiserName = "全部广告主";
        if (null == paramMap.get("selectedAdvertiserId") || "".equals(paramMap.get("selectedAdvertiserId"))) {
            advertiserName = "全部广告主";
        } else {
            if (-1 == Long.parseLong((String) paramMap.get("selectedAdvertiserId"))) {
                advertiserName = "全部广告主";
            } else {
                advertiserId = Long.parseLong((String) paramMap.get("selectedAdvertiserId"));
                advertiserName = advertiserService.findById(advertiserId).getName();
            }
        }

        paramMap.put("agentId", agentId);
        paramMap.put("advertiserId", advertiserId);
        paramMap.put("selectedAdvertiserName", advertiserName);

        List<Finance> financeList = financeService.findByParams(paramMap);
        paramMap.put("dataList", financeList);
        response.reset();
        // Content-Type:application/vnd.ms-excel;charset=utf8或者text/xml;charset=utf8
        response.setContentType("application/vnd.ms-excel;charset=utf8");
        // 设置excel文件名称
        SimpleDateFormat df2 = new SimpleDateFormat("yyyyMMddHHmmss");
        String fileName = "balanceReport" + df2.format(new Date());
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xls");
        // 需要对excel的列的总数进行指定
        int column = 10;
        paramMap.put("dataSize", (financeList.size() + 100));
        paramMap.put("column", column);
        String excelOrder = templateProcessor.processTemplate("excel/balanceReport.ftl", paramMap);
        try {
            PrintWriter out = response.getWriter();
            out.write(excelOrder);
            out.flush();
            out.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}